package com.befirefly.studentmanager.service.impl;

import com.befirefly.studentmanager.entity.StudentDO;
import com.befirefly.studentmanager.mapper.StudentMapper;
import com.befirefly.studentmanager.req.StudentRequest;
import com.befirefly.studentmanager.res.TableDTO;
import com.befirefly.studentmanager.service.StudentService;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Vector;

/**
 * @Author: 八千里路云和月
 * @Date: 2021/2/8 14:03
 * @Description:
 */
public class StudentServiceImpl implements StudentService {
    @Override
    public TableDTO retrieveStudents(StudentRequest request) {
        TableDTO returnDTO = new TableDTO();
        Vector<Vector<Object>> rawData = new Vector<>();
        Vector<Vector<Object>> data = new Vector<>();
        int totalCount = 0;
        int offset;
        int rows;
        if (StringUtils.isBlank(request.getSearchKey())) {
            rawData = StudentMapper.selectAll();
            offset = request.getStart();
            rows = request.getStart() + request.getPageSize();
            totalCount = StudentMapper.selectTotalCount();
            if (rows >= totalCount) {
                rows = totalCount;
            }
            List<Vector<Object>> vectorList = rawData.subList(offset, rows);
            data = new Vector<>(vectorList);
        } else {
            rawData = StudentMapper.selectBySearchKey(request);
            offset = request.getStart();
            rows = request.getStart() + request.getPageSize();
            totalCount = rawData.size();
            if (rows >= totalCount) {
                rows = totalCount;
            }
            List<Vector<Object>> vectorList = rawData.subList(offset, rows);
            data = new Vector<>(vectorList);
        }
        returnDTO.setData(data);
        returnDTO.setTotalCount(totalCount);
        return returnDTO;
    }

    @Override
    public boolean add(StudentDO studentDO) {
        return StudentMapper.add(studentDO);
    }

    @Override
    public StudentDO selectById(long selectedStudentId) {
        StudentDO studentDO = new StudentDO();
        studentDO = StudentMapper.selectById(selectedStudentId);
        if (studentDO != null) {
            return studentDO;
        }
        return null;
    }

    @Override
    public boolean update(StudentDO studentDO) {

        return StudentMapper.updateById(studentDO);
    }

    @Override
    public boolean delete(long[] selectedStudentIds) {
        for (Long id : selectedStudentIds) {
            boolean deleteResult = StudentMapper.deleteById(id);
            if (BooleanUtils.isFalse(deleteResult)) {
                return false;
            }
        }
        return true;
    }
}
